import re
from flask import request, jsonify, current_app, session
from sqlalchemy.exc import IntegrityError

from ihome import redis_store, db
from ihome.api_1_0 import api
from ihome.models import User
from ihome.utils.response_code import RET


@api.route('/users', methods=['POST'])
def register():
    req_data = request.get_json()
    mobile = req_data.get('mobile')
    sms_code = req_data.get('sms_code')
    password = req_data.get('password')
    password2 = req_data.get('password2')
    # request.referrer

    if not all([mobile, sms_code, password, password2]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码格式有误")

    try:
        real_sms_code = redis_store.get('SMSCode_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码有误")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")

    user_obj = User()
    user_obj.name = mobile
    user_obj.mobile = mobile
    user_obj.password = password

    try:
        db.session.add(user_obj)
        db.session.commit()
    except IntegrityError as e:
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="注册失败")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="该手机号已经被注册了")

    session['mobile'] = mobile
    session['name'] = mobile
    session['user_id'] = user_obj.id

    return jsonify(errno=RET.OK, errmsg="注册成功")


@api.route('/sessions', methods=['POST'])
def login():
    user_ip = request.remote_addr
    data = request.get_json()
    mobile = data.get('mobile')
    password = data.get('password')

    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码格式有误")

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取数据失败")

    if user is None or not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg="账号或密码错误")

    session['user_id'] = user.id
    session['name'] = user.name
    session['mobile'] = user.mobile

    return jsonify(errno=RET.OK, errmsg="登录成功")


@api.route("/session", methods=["GET"])
def check_login():
    """检查登陆状态"""
    # 尝试从session中获取用户的名字
    name = session.get("name")
    # 如果session中数据name名字存在，则表示用户已登录，否则未登录
    if name is not None:
        return jsonify(errno=RET.OK, errmsg="true", data={"name": name})
    else:
        return jsonify(errno=RET.SESSIONERR, errmsg="false")


@api.route('/session', methods=['DELETE'])
def logout():
    """
    # 清除session数据
    csrf_token = session.get("csrf_token")
    session.clear()
    session["csrf_token"] = csrf_token
    return jsonify(errno=RET.OK, errmsg="OK")
    :return: 
    """
    csrf_token = session.get("csrf_token")
    session.clear()
    session["csrf_token"] = csrf_token
    return jsonify(errno=RET.OK, errmsg="OK")
